﻿Shader "Decal"
{
    Properties
    {
        _BaseColor("Color",Color) = (1,1,1,1)
        _BaseMap("Texture",2D) = "white"{}
    }
    SubShader
    {
        Tags
        {
            "RenderPipeline"="UniversalRenderPipeline"
            "RenderType"="Overlay"
            "Queue"="Geometry+1"
        }
        ZWrite Off
        Blend SrcAlpha OneMinusSrcAlpha

        HLSLINCLUDE
        #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"

        TEXTURE2D(_BaseMap);
        SAMPLER(sampler_BaseMap);

        TEXTURE2D(_CameraDepthTexture);
        SAMPLER(sampler_CameraDepthTexture);

        CBUFFER_START(UnityPerMaterial)
        float4 _BaseMap_ST;
        half4 _BaseColor;
        CBUFFER_END
        ENDHLSL

        pass
        {
            HLSLPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            struct a2v
            {
                float4 positionOS : POSITION;
                float2 texcoord : TEXCOORD;
            };

            struct v2f
            {
                float4 positionCS : SV_POSITION;
                float4 screenUV : TEXCOORDO;
                float3 cameraRay : TEXCOORD;
            };

            v2f vert(a2v v)
            {
                v2f o;
                o.positionCS = TransformObjectToHClip(v.positionOS.xyz);
                //计算屏幕空间
                o.screenUV = ComputeScreenPos(o.positionCS);
                //世界空间 TO 相机空间
                o.cameraRay = TransformWorldToView(TransformObjectToWorld(v.positionOS.xyz)).xyz * float3(-1, -1, 1);

                return o;
            }

            half4 frag(v2f i):SV_Target
            {
                //片元透视除法计算屏幕uv
                half2 screenUV = i.screenUV.xy / i.screenUV.w;
                //片元透视除法计算相机射线
                i.cameraRay = i.cameraRay * (_ProjectionParams.z / i.cameraRay.z);
                //采样深度贴图
                float depth = SAMPLE_TEXTURE2D(_CameraDepthTexture, sampler_CameraDepthTexture, screenUV).x;
                //要转换成线性的深度值
                depth = Linear01Depth(depth, _ZBufferParams);

                half4 positionVS = float4(i.cameraRay * depth, 1);
                half3 positionWS = mul(unity_CameraToWorld, positionVS).xyz;
                half3 positionOS = mul(unity_WorldToObject, float4(positionWS, 1)).xyz;

                half4 albedo = SAMPLE_TEXTURE2D(_BaseMap, sampler_BaseMap, positionOS.xz + 0.5);
                //裁剪
                clip(half3(0.5, 0.5, 0.5) - abs(positionOS.xyz));
                return albedo;

                return 1;
            }
            ENDHLSL
        }
    }
}